<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// Create uploads directory if it doesn't exist
$uploadsDir = dirname(__DIR__) . '/uploads';
$carsDir = $uploadsDir . '/cars';

// Create directories with proper permissions if they don't exist
if (!file_exists($uploadsDir)) {
    mkdir($uploadsDir, 0777, true);
    chmod($uploadsDir, 0777);
}

if (!file_exists($carsDir)) {
    mkdir($carsDir, 0777, true);
    chmod($carsDir, 0777);
}

// Debug logging
error_log("Upload attempt started");

if (!is_admin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (isset($_FILES['images'])) {
    $file = [
        'name' => $_FILES['images']['name'][0],
        'type' => $_FILES['images']['type'][0],
        'tmp_name' => $_FILES['images']['tmp_name'][0],
        'error' => $_FILES['images']['error'][0],
        'size' => $_FILES['images']['size'][0]
    ];
    
    // Debug file info
    error_log("File info: " . print_r($file, true));
    
    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/exr', 'image/bmp', 'image/tiff', 'image/webp'];
    if (!in_array($file['type'], $allowed_types)) {
        error_log("Invalid file type: " . $file['type']);
        echo json_encode(['success' => false, 'message' => 'Invalid file type']);
        exit;
    }
    
    // Validate file size (max 5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'File too large']);
        exit;
    }

    $uploadDir = $carsDir . '/';
    error_log("Upload directory: " . $uploadDir);
    
    // Check directory permissions
    error_log("Directory writable: " . (is_writable($uploadDir) ? 'yes' : 'no'));

    $fileName = uniqid() . '_' . sanitize_input($file['name']);
    $uploadPath = $uploadDir . $fileName;
    
    error_log("Attempting to move file to: " . $uploadPath);
    
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        error_log("File uploaded successfully");
        echo json_encode([
            'success' => true,
            'path' => 'uploads/cars/' . $fileName
        ]);
    } else {
        $error = error_get_last();
        error_log("Upload failed: " . ($error ? $error['message'] : 'Unknown error'));
        echo json_encode([
            'success' => false,
            'message' => 'Upload failed: ' . ($error ? $error['message'] : 'Unknown error')
        ]);
    }
    exit;
}

error_log("No file received in upload request");
echo json_encode(['success' => false, 'message' => 'No file uploaded']); 